﻿using BasicInformation.ApiWrite.Application.Command.Device;
using BasicInformation.ApiWrite.Application.Handler.Depot;
using BasicInformation.Domain;
using BasicInformation.ErrorCode;
using BasicInformation.Infrastructure.Implement;
using MediatR;

namespace BasicInformation.ApiWrite.Application.Handler.Device
{
    public class DelDeviceHandler : IRequestHandler<DelDeviceCommand, ApiResult<int>>
    {
        private readonly DatabaseContext db;
        private readonly ILogger<DelDeviceHandler> logger;

        public DelDeviceHandler(DatabaseContext db, ILogger<DelDeviceHandler> logger)
        {
            this.db = db;
            this.logger = logger;
        }
        public async Task<ApiResult<int>> Handle(DelDeviceCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> result = new ApiResult<int>();
            var device = db.SqlSugar.Queryable<DeviceModel>().Where(x => x.DeviceId == request.DeviceId).First();
            device.IsDel = true;
            int r = await db.SqlSugar.Updateable(device).ExecuteCommandAsync();
            if (r > 0)
            {
                result.Msg = "设备管理删除成功";
                result.Data = r;
                result.Code = ApiEnum.OK;
                logger.LogInformation(result.Msg);
            }
            else
            {
                result.Msg = "设备管理删除失败";
                result.Data = r;
                result.Code = ApiEnum.Fail;
                logger.LogError(result.Msg);
            }
            return await Task.FromResult(result);
        }
    }
}
